#!/usr/bin/env python
# -*- coding: utf8 -*-
import sys
from xml.etree import ElementTree
from xml.etree.ElementTree import Element, SubElement
from lxml import etree
import codecs

XML_EXT = '.xml'
ENCODE_METHOD = 'utf-8'


class PascalVocWriter:
    def __init__(self, foldername, filename, imgSize, databaseSrc='widerface', localImgPath=None):
        self.foldername = foldername
        self.filename = filename
        self.databaseSrc = databaseSrc
        self.imgSize = imgSize
        self.objectList = []
        self.localImgPath = localImgPath
        self.verified = False

    def prettify(self, elem):
        """
            Return a pretty-printed XML string for the Element.
        """
        rough_string = ElementTree.tostring(elem, 'utf8')
        root = etree.fromstring(rough_string)
        return etree.tostring(root, pretty_print=True, encoding=ENCODE_METHOD).replace("  ".encode(), "\t".encode())
        # minidom does not support UTF-8
        '''reparsed = minidom.parseString(rough_string)
        return reparsed.toprettyxml(indent="\t", encoding=ENCODE_METHOD)'''

    def genXML(self):
        """
            Return XML root
        """
        # Check conditions
        if self.filename is None or \
                self.foldername is None or \
                self.imgSize is None:
            return None

        top = Element('annotation')
        if self.verified:
            top.set('verified', 'yes')

        folder = SubElement(top, 'folder')
        folder.text = self.foldername

        filename = SubElement(top, 'filename')
        filename.text = self.filename

        if self.localImgPath is not None:
            localImgPath = SubElement(top, 'path')
            localImgPath.text = self.localImgPath

        source = SubElement(top, 'source')
        database = SubElement(source, 'database')
        database.text = self.databaseSrc

        size_part = SubElement(top, 'size')
        width = SubElement(size_part, 'width')
        height = SubElement(size_part, 'height')
        depth = SubElement(size_part, 'depth')
        width.text = str(self.imgSize[1])
        height.text = str(self.imgSize[0])
        if len(self.imgSize) == 3:
            depth.text = str(self.imgSize[2])
        else:
            depth.text = '1'
        return top

    def addBndBox(self, bndbox, landmarks, name, gender, mask, glass, hat, cellphone, smoking, yawpose, blur,
                  expression, illumination, occlusion, pose, invalid):
        object = {}
        object['xmin'] = bndbox[0]
        object['ymin'] = bndbox[1]
        object['xmax'] = bndbox[2]
        object['ymax'] = bndbox[3]
        if landmarks:
            object['lm_x1'] = int(landmarks[0][0])
            object['lm_y1'] = int(landmarks[0][1])
            object['lm_x2'] = int(landmarks[1][0])
            object['lm_y2'] = int(landmarks[1][1])
            object['lm_x3'] = int(landmarks[2][0])
            object['lm_y3'] = int(landmarks[2][1])
            object['lm_x4'] = int(landmarks[3][0])
            object['lm_y4'] = int(landmarks[3][1])
            object['lm_x5'] = int(landmarks[4][0])
            object['lm_y5'] = int(landmarks[4][1])
        else:
            object['lm_x1'] = int(-1)
            object['lm_y1'] = int(-1)
            object['lm_x2'] = int(-1)
            object['lm_y2'] = int(-1)
            object['lm_x3'] = int(-1)
            object['lm_y3'] = int(-1)
            object['lm_x4'] = int(-1)
            object['lm_y4'] = int(-1)
            object['lm_x5'] = int(-1)
            object['lm_y5'] = int(-1)
        object['name'] = name
        object['gender'] = gender
        object['mask'] = mask
        object['glass'] = glass
        object['hat'] = hat
        object['cellphone'] = cellphone
        object['smoking'] = smoking
        object['yawpose'] = yawpose
        object['blur'] = blur
        object['expression'] = expression
        object['illumination'] = illumination
        object['occlusion'] = occlusion
        object['pose'] = pose
        object['invalid'] = invalid
        self.objectList.append(object)

    def appendObjects(self, top):
        for each_object in self.objectList:
            object_item = SubElement(top, 'object')
            name = SubElement(object_item, 'name')
            try:
                name.text = unicode(each_object['name'])
            except NameError:
                # Py3: NameError: name 'unicode' is not defined
                name.text = each_object['name']

            gender = SubElement(object_item, 'gender')
            gender.text = str(each_object['gender'])

            mask = SubElement(object_item, 'mask')
            mask.text = str(each_object['mask'])

            glass = SubElement(object_item, 'glass')
            glass.text = str(each_object['glass'])

            hat = SubElement(object_item, 'hat')
            hat.text = str(each_object['hat'])

            cellphone = SubElement(object_item, 'cellphone')
            cellphone.text = str(each_object['cellphone'])

            smoking = SubElement(object_item, 'smoking')
            smoking.text = str(each_object['smoking'])

            yawpose = SubElement(object_item, 'yawpose')
            yawpose.text = str(each_object['yawpose'])

            blur = SubElement(object_item, 'blur')
            blur.text = str(each_object['blur'])

            expression = SubElement(object_item, 'expression')
            expression.text = str(each_object['expression'])

            illumination = SubElement(object_item, 'illumination')
            illumination.text = str(each_object['illumination'])

            occlusion = SubElement(object_item, 'occlusion')
            occlusion.text = str(each_object['occlusion'])

            pose = SubElement(object_item, 'pose')
            pose.text = str(each_object['pose'])

            invalid = SubElement(object_item, 'invalid')
            invalid.text = str(each_object['invalid'])

            bndbox = SubElement(object_item, 'bndbox')
            xmin = SubElement(bndbox, 'xmin')
            xmin.text = str(each_object['xmin'])
            ymin = SubElement(bndbox, 'ymin')
            ymin.text = str(each_object['ymin'])
            xmax = SubElement(bndbox, 'xmax')
            xmax.text = str(each_object['xmax'])
            ymax = SubElement(bndbox, 'ymax')
            ymax.text = str(each_object['ymax'])

            landmarks = SubElement(object_item, 'landmarks')
            lm_x1 = SubElement(landmarks, 'lm_x1')
            lm_x1.text = str(each_object['lm_x1'])
            lm_y1 = SubElement(landmarks, 'lm_y1')
            lm_y1.text = str(each_object['lm_y1'])
            lm_x2 = SubElement(landmarks, 'lm_x2')
            lm_x2.text = str(each_object['lm_x2'])
            lm_y2 = SubElement(landmarks, 'lm_y2')
            lm_y2.text = str(each_object['lm_y2'])
            lm_x3 = SubElement(landmarks, 'lm_x3')
            lm_x3.text = str(each_object['lm_x3'])
            lm_y3 = SubElement(landmarks, 'lm_y3')
            lm_y3.text = str(each_object['lm_y3'])
            lm_x4 = SubElement(landmarks, 'lm_x4')
            lm_x4.text = str(each_object['lm_x4'])
            lm_y4 = SubElement(landmarks, 'lm_y4')
            lm_y4.text = str(each_object['lm_y4'])
            lm_x5 = SubElement(landmarks, 'lm_x5')
            lm_x5.text = str(each_object['lm_x5'])
            lm_y5 = SubElement(landmarks, 'lm_y5')
            lm_y5.text = str(each_object['lm_y5'])

    def save(self, targetFile=None):
        root = self.genXML()
        self.appendObjects(root)
        out_file = None
        if targetFile is None:
            out_file = codecs.open(
                self.filename + XML_EXT, 'w', encoding=ENCODE_METHOD)
        else:
            out_file = codecs.open(targetFile, 'w', encoding=ENCODE_METHOD)

        prettifyResult = self.prettify(root)
        out_file.write(prettifyResult.decode('utf8'))
        out_file.close()


class PascalVocReader:

    def __init__(self, filepath):
        # shapes type:
        # [labbel, [(x1,y1), (x2,y2), (x3,y3), (x4,y4)], color, color, ismale]
        self.shapes = []
        self.filepath = filepath
        self.verified = False
        try:
            self.parseXML()
        except:
            pass

    def getShapes(self):
        return self.shapes

    def addShape(self, label, bndbox, landmarks,
                 gender,
                 mask,
                 glass, hat, cellphone, smoking, yawpose, blur, expression, illumination, occlusion, pose, invalid):
        xmin = int(bndbox.find('xmin').text)
        ymin = int(bndbox.find('ymin').text)
        xmax = int(bndbox.find('xmax').text)
        ymax = int(bndbox.find('ymax').text)
        bndbox = [xmin, ymin, xmax, ymax]
        points = [(xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax)]
        if landmarks is not None:
            lm_x1 = int(landmarks.find('lm_x1').text)
            lm_y1 = int(landmarks.find('lm_y1').text)
            lm_x2 = int(landmarks.find('lm_x2').text)
            lm_y2 = int(landmarks.find('lm_y2').text)
            lm_x3 = int(landmarks.find('lm_x3').text)
            lm_y3 = int(landmarks.find('lm_y3').text)
            lm_x4 = int(landmarks.find('lm_x4').text)
            lm_y4 = int(landmarks.find('lm_y4').text)
            lm_x5 = int(landmarks.find('lm_x5').text)
            lm_y5 = int(landmarks.find('lm_y5').text)
        else:
            lm_x1 = int(-1)
            lm_y1 = int(-1)
            lm_x2 = int(-1)
            lm_y2 = int(-1)
            lm_x3 = int(-1)
            lm_y3 = int(-1)
            lm_x4 = int(-1)
            lm_y4 = int(-1)
            lm_x5 = int(-1)
            lm_y5 = int(-1)
        landmarks = [(lm_x1, lm_y1), (lm_x2, lm_y2), (lm_x3, lm_y3), (lm_x4, lm_y4), (lm_x5, lm_y5)]
        self.shapes.append((label, bndbox, landmarks,
                            gender,
                            mask,
                            glass, hat, cellphone, smoking, yawpose, blur, expression, illumination, occlusion, pose,
                            invalid))

    def parseXML(self):
        assert self.filepath.endswith(XML_EXT), "Unsupport file format"
        parser = etree.XMLParser(encoding=ENCODE_METHOD)
        xmltree = ElementTree.parse(self.filepath, parser=parser).getroot()
        if xmltree.find('filename') is not None:
            filename = xmltree.find('filename').text
        try:
            verified = xmltree.attrib['verified']
            if verified == 'yes':
                self.verified = True
        except KeyError:
            self.verified = False

        for object_iter in xmltree.findall('object'):
            bndbox = object_iter.find("bndbox")
            label = object_iter.find('name').text

            landmarks = object_iter.find("landmarks")

            # Add chris
            gender = -1
            mask = -1
            glass = -1
            hat = -1
            cellphone = -1
            smoking = -1
            yawpose = -1
            blur = -1
            expression = -1
            illumination = -1
            occlusion = -1
            pose = -1
            invalid = -1

            if object_iter.find('gender') is not None:
                gender = int(object_iter.find('gender').text)

            if object_iter.find('mask') is not None:
                mask = int(object_iter.find('mask').text)

            if object_iter.find('glass') is not None:
                glass = int(object_iter.find('glass').text)

            if object_iter.find('hat') is not None:
                hat = int(object_iter.find('hat').text)

            if object_iter.find('cellphone') is not None:
                cellphone = int(object_iter.find('cellphone').text)

            if object_iter.find('smoking') is not None:
                smoking = int(object_iter.find('smoking').text)

            if object_iter.find('yawpose') is not None:
                yawpose = int(object_iter.find('yawpose').text)

            if object_iter.find('blur') is not None:
                blur = int(object_iter.find('blur').text)

            if object_iter.find('expression') is not None:
                expression = int(object_iter.find('expression').text)

            if object_iter.find('illumination') is not None:
                illumination = int(object_iter.find('illumination').text)

            if object_iter.find('occlusion') is not None:
                occlusion = int(object_iter.find('occlusion').text)

            if object_iter.find('pose') is not None:
                pose = int(object_iter.find('pose').text)

            if object_iter.find('invalid') is not None:
                invalid = int(object_iter.find('invalid').text)

            self.addShape(label, bndbox, landmarks,
                          gender,
                          mask,
                          glass, hat, cellphone, smoking, yawpose, blur, expression, illumination, occlusion, pose,
                          invalid)
        return True
